import sqlite3
import time

import gevent
from gevent import monkey

monkey.patch_all()  # 一键替换多进程多线程关键字


def connect():
    conn = sqlite3.connect('example.db')
    cur = conn.cursor()
    return conn, cur


def create_table():
    conn, cur = connect()
    cur.execute('''CREATE TABLE stocks
               (date text, trans text, symbol text, qty real, price real)''')
    conn.commit()
    cur.close()
    conn.close()


def insert_one():
    print('begin')
    time.sleep(1)
    conn, cur = connect()
    cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
    conn.commit()
    cur.close()
    conn.close()
    print('end')


def query_all():
    print('begin')
    conn, cur = connect()
    cur.execute('SELECT * FROM stocks ORDER BY price')
    cur.close()
    conn.close()
    print('end')


def gevent_demo(func):
    """非阻塞式执行多个请求"""

    # 生成事件清单
    tasks = [gevent.spawn(func) for i in range(5)]
    # 把清单加入事件循环队列中
    gevent.joinall(tasks)


def story_read():
    print('begin')
    story_path = '神秘复苏.txt'
    f = open(story_path, encoding='gb18030', errors='ignore')
    f.read()
    print('end')


if __name__ == '__main__':
    # insert_one()
    # query_all()
    # query_all()
    # query_all()
    gevent_demo(story_read)
